using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using Newtonsoft.Json;

namespace WindowsFormsDataBaice
{
    public partial class PrescriptionForm : Form
    {
        private int visitId;
        private ComboBox cmbPrescriptionType;
        private TextBox txtDrugCode;
        private TextBox txtDrugName;
        private TextBox txtSpec;
        private NumericUpDown nudQty;
        private TextBox txtUnit;
        private NumericUpDown nudDays;
        private NumericUpDown nudPrice;
        private Label lblAmount;
        private Button btnConfirm;
        private Button btnCancel;

        public PrescriptionForm(int visitId)
        {
            this.visitId = visitId;
            InitializeComponent();
        }

        private void InitializeComponent()
        {
            this.Text = "开处方";
            this.Size = new System.Drawing.Size(400, 350);
            this.StartPosition = FormStartPosition.CenterParent;
            this.FormBorderStyle = FormBorderStyle.FixedDialog;
            this.MaximizeBox = false;
            this.MinimizeBox = false;

            // 处方类型
            var lblType = new Label { Text = "处方类型:", Location = new System.Drawing.Point(20, 20), Size = new System.Drawing.Size(80, 23) };
            cmbPrescriptionType = new ComboBox 
            { 
                Location = new System.Drawing.Point(110, 20), 
                Size = new System.Drawing.Size(200, 23),
                DropDownStyle = ComboBoxStyle.DropDownList
            };
            cmbPrescriptionType.Items.AddRange(new[] { "西药", "中成药" });
            cmbPrescriptionType.SelectedIndex = 0;

            // 药品编码
            var lblDrugCode = new Label { Text = "药品编码:", Location = new System.Drawing.Point(20, 60), Size = new System.Drawing.Size(80, 23) };
            txtDrugCode = new TextBox { Location = new System.Drawing.Point(110, 60), Size = new System.Drawing.Size(200, 23) };

            // 药品名称
            var lblDrugName = new Label { Text = "药品名称:", Location = new System.Drawing.Point(20, 100), Size = new System.Drawing.Size(80, 23) };
            txtDrugName = new TextBox { Location = new System.Drawing.Point(110, 100), Size = new System.Drawing.Size(200, 23) };

            // 规格
            var lblSpec = new Label { Text = "规格:", Location = new System.Drawing.Point(20, 140), Size = new System.Drawing.Size(80, 23) };
            txtSpec = new TextBox { Location = new System.Drawing.Point(110, 140), Size = new System.Drawing.Size(200, 23) };

            // 数量
            var lblQty = new Label { Text = "数量:", Location = new System.Drawing.Point(20, 180), Size = new System.Drawing.Size(80, 23) };
            nudQty = new NumericUpDown 
            { 
                Location = new System.Drawing.Point(110, 180), 
                Size = new System.Drawing.Size(100, 23),
                Minimum = 1,
                Maximum = 999,
                Value = 1
            };

            // 单位
            var lblUnit = new Label { Text = "单位:", Location = new System.Drawing.Point(220, 180), Size = new System.Drawing.Size(40, 23) };
            txtUnit = new TextBox { Location = new System.Drawing.Point(270, 180), Size = new System.Drawing.Size(40, 23) };
            txtUnit.Text = "盒";

            // 天数
            var lblDays = new Label { Text = "天数:", Location = new System.Drawing.Point(20, 220), Size = new System.Drawing.Size(80, 23) };
            nudDays = new NumericUpDown 
            { 
                Location = new System.Drawing.Point(110, 220), 
                Size = new System.Drawing.Size(100, 23),
                Minimum = 1,
                Maximum = 30,
                Value = 3
            };

            // 单价
            var lblPrice = new Label { Text = "单价:", Location = new System.Drawing.Point(220, 220), Size = new System.Drawing.Size(40, 23) };
            nudPrice = new NumericUpDown 
            { 
                Location = new System.Drawing.Point(270, 220), 
                Size = new System.Drawing.Size(70, 23),
                Minimum = 0,
                Maximum = 9999,
                DecimalPlaces = 2,
                Value = 0
            };

            // 总金额
            var lblAmountText = new Label { Text = "总金额:", Location = new System.Drawing.Point(20, 260), Size = new System.Drawing.Size(80, 23) };
            lblAmount = new Label 
            { 
                Text = "0.00元", 
                Location = new System.Drawing.Point(110, 260), 
                Size = new System.Drawing.Size(100, 23),
                ForeColor = System.Drawing.Color.Red
            };

            // 按钮
            btnConfirm = new Button 
            { 
                Text = "确认开处方", 
                Location = new System.Drawing.Point(200, 290), 
                Size = new System.Drawing.Size(80, 30),
                DialogResult = DialogResult.OK
            };
            btnCancel = new Button 
            { 
                Text = "取消", 
                Location = new System.Drawing.Point(290, 290), 
                Size = new System.Drawing.Size(60, 30),
                DialogResult = DialogResult.Cancel
            };

            // 事件绑定
            nudQty.ValueChanged += CalculateAmount;
            nudDays.ValueChanged += CalculateAmount;
            nudPrice.ValueChanged += CalculateAmount;
            btnConfirm.Click += BtnConfirm_Click;

            // 添加控件
            this.Controls.AddRange(new Control[]
            {
                lblType, cmbPrescriptionType,
                lblDrugCode, txtDrugCode,
                lblDrugName, txtDrugName,
                lblSpec, txtSpec,
                lblQty, nudQty, lblUnit, txtUnit,
                lblDays, nudDays, lblPrice, nudPrice,
                lblAmountText, lblAmount,
                btnConfirm, btnCancel
            });

            CalculateAmount(null, null);
        }

        private void CalculateAmount(object sender, EventArgs e)
        {
            decimal amount = (decimal)nudQty.Value * (decimal)nudDays.Value * nudPrice.Value;
            lblAmount.Text = amount.ToString("F2") + "元";
        }

        private async void BtnConfirm_Click(object sender, EventArgs e)
        {
            // 验证输入
            if (string.IsNullOrWhiteSpace(txtDrugCode.Text))
            {
                MessageBox.Show("请输入药品编码", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtDrugCode.Focus();
                return;
            }

            if (string.IsNullOrWhiteSpace(txtDrugName.Text))
            {
                MessageBox.Show("请输入药品名称", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
                txtDrugName.Focus();
                return;
            }

            try
            {
                // 构建处方数据
                var prescriptionData = new
                {
                    visitId = this.visitId,
                    type = cmbPrescriptionType.SelectedItem.ToString(),
                    items = new[]
                    {
                        new
                        {
                            drugCode = txtDrugCode.Text.Trim(),
                            drugName = txtDrugName.Text.Trim(),
                            spec = txtSpec.Text.Trim(),
                            qty = (int)nudQty.Value,
                            unit = txtUnit.Text.Trim(),
                            days = (int)nudDays.Value,
                            price = nudPrice.Value,
                            amount = (decimal)nudQty.Value * (decimal)nudDays.Value * nudPrice.Value
                        }
                    }
                };

                using (HttpClient client = new HttpClient())
                {
                    client.Timeout = TimeSpan.FromSeconds(30);
                    string json = JsonConvert.SerializeObject(prescriptionData);
                    var content = new StringContent(json, Encoding.UTF8, "application/json");

                    string url = "http://101.201.170.32:5166/api/DoctorWorkstation/add-prescription";
                    var response = await client.PostAsync(url, content);
                    string responseContent = await response.Content.ReadAsStringAsync();

                    if (response.IsSuccessStatusCode)
                    {
                        dynamic apiResponse = JsonConvert.DeserializeObject(responseContent);
                        if (apiResponse?.code == 200)
                        {
                            this.DialogResult = DialogResult.OK;
                            this.Close();
                        }
                        else
                        {
                            string errorMessage = apiResponse?.msg?.ToString() ?? "添加处方失败";
                            MessageBox.Show(errorMessage, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        }
                    }
                    else
                    {
                        MessageBox.Show($"请求失败: {response.StatusCode}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"网络请求失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
} 